﻿using System;
using Consul;
using InvestService.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace InvestService
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IFoo, Foo>()
                .AddSingleton<IBar, Bar>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime applicationLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
            var ip = Configuration["ip"];
            var port = Configuration["port"];
            var serviceName = "InvestService";
            var serviceId = $"{serviceName }:{Guid.NewGuid()}";
            using (var consulClient = new ConsulClient(ConsulConfig))
            {
                AgentServiceRegistration service = new AgentServiceRegistration()
                {
                    ID = serviceId,
                    Name = serviceName,
                    Address = ip,
                    Port = Convert.ToInt32(port),
                    Check = new AgentServiceCheck()
                    {
                        HTTP = $"http://{ip}:{port}/api/health",
                        Interval = TimeSpan.FromSeconds(10),
                        Timeout = TimeSpan.FromSeconds(5),
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5)
                    }
                };

                consulClient.Agent.ServiceRegister(service).Wait();
            }

            applicationLifetime.ApplicationStopped.Register(() =>
            {
                using (var consulClient = new ConsulClient(ConsulConfig))
                {
                    Console.WriteLine("应用推送，开始从Consul注销");
                    consulClient.Agent.ServiceDeregister(serviceId).Wait();
                }
            });
        }

        private void ConsulConfig(ConsulClientConfiguration consulClientConfiguration)
        {
            consulClientConfiguration.Address = new Uri("http://127.0.0.1:8500");
            consulClientConfiguration.Datacenter = "dc1";
        }
    }
}
